package com.zhiying.until.ipadderss;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

public class IpAddress {
	
	/**
	 * 获取当前网络ip
	 * @return
	 */
	public  static HttpServletRequest  getRequest(HttpServletRequest req) {
//		((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest()
		return req;
	}
	
	public static String getIpAddr(HttpServletRequest req) {
		String ipAddress = getRequest(req).getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = getRequest(req).getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = getRequest(req).getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = getRequest(req).getRemoteAddr();
			if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
//					logger.error("ServletUtils.getIpAddr", e);
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15 && ipAddress.indexOf(',') > 0) {
			ipAddress = ipAddress.substring(0, ipAddress.indexOf(','));
		}
		return ipAddress;
	}
	/**
	 * 获取当前用户游览器信息
	 */
	public static String getHeader(HttpServletRequest req) {
		return getRequest(req).getHeader("User-Agent");
	}
	

	/**
	 * 获取当前用户游览器型号
	 */
	public static String getUserBrowser(HttpServletRequest req) {
		UserAgent userAgent = UserAgent.parseUserAgentString(getRequest(req).getHeader("User-Agent"));
		Browser browser = userAgent.getBrowser();
		return browser.toString();
	}
	
	/**
	 * 获取当前用户系统型号
	 */
	public static String getUserOperatingSystem(HttpServletRequest req) {
		UserAgent userAgent = UserAgent.parseUserAgentString(getRequest(req).getHeader("User-Agent"));
		OperatingSystem operatingSystem = userAgent.getOperatingSystem();
		return operatingSystem.toString();
	}

}
